package com.hong.listener.impl;

import com.hong.Config.RpcServerConfig;
import com.hong.RpcServer;
import com.hong.listener.Listener;
import com.hong.listener.ListenerManager;
import com.hong.listener.RpcServerListener;
import com.hong.qrpc.utils.ReflectionUtils;

import java.util.HashSet;
import java.util.Map;

/**
 * @Author HQT
 * @Date 2022/7/22 20:45
 */
public class RpcServerConfigurer implements RpcServerListener {
    private String helpCompare = "com.hong.listener.impl.RpcServerConfigurer";

    @Override
    public void afterRpcServerInit(RpcServer rpcServer) {
        RpcServerConfig config = rpcServer.getConfigManager().getRpcServerConfig();
        rpcServer.setNet(ReflectionUtils.newInstance(config.getTransportClass()));
        rpcServer.getNet().init(config.getPort(), config.getProtocolType(), rpcServer.getHandler());
    }

    public static void addListener(ListenerManager listenerManager) {
        Map<Class<? extends Listener>, HashSet<Listener>> listenerSets = listenerManager.getListenerSets();
        HashSet<Listener> listeners = listenerSets.get(RpcServerListener.class);
        if (listeners == null) {
            listeners = new HashSet<>();
            listenerSets.put(RpcServerListener.class, listeners);
        }
        RpcServerConfigurer rsc = new RpcServerConfigurer();
        if (!listeners.contains(rsc)) {
            listeners.add(rsc);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RpcServerConfigurer that = (RpcServerConfigurer) o;

        return helpCompare.equals(that.helpCompare);
    }

    @Override
    public int hashCode() {
        return helpCompare.hashCode();
    }
}
